import React from 'react'
// ===================================================================== Temp
import SearchForm from '#cpt/temp/SearchForm'
import Table from '#cpt/temp/Table'
import Controls from '#cpt/temp/Controls'
import Confirm from '#cpt/temp/Confirm'
import Tabs from '#tp/tabs/tabs'
import { Status, CaseType, CardType,Sex,MultipleType,CheckType } from '@views/novel-coro-system/test-info/common/defaultData'
// ===================================================================== global declare
const { $fn, $http, $Lazy, globalConfig } = window
const { COVIDUrl } = globalConfig
// ===================================================================== private component
const Page 				= $Lazy.load(()=>import('#tp/page/page-container'))
const BtnGroup 			= $Lazy.load(()=>import('#tp/btn-group'))
const $cache 			= $Lazy.file(()=>import('#private/cache-api'))
const $time 			= $Lazy.file(()=>import('@com/utils/time'))
const PatientDetail 	= $Lazy.state(()=>import('./cpt/patient-detail'))
const HospModifyModal 	= $Lazy.state(()=>import('./cpt/hosp-modify-modal'))
const ChangeHospModal 	= $Lazy.state(()=>import('./cpt/change-hosp-modal'))
const ChangeSpecModal 	= $Lazy.state(()=>import('./cpt/change-spec-modal'))
const SampTimeModal		= $Lazy.state(()=>import('./cpt/samp-time-modal'))
const AbnormalInfoModal		= $Lazy.state(()=>import('./cpt/abnormal-info-modal'))
// ===================================================================== data
const tabsData = [{ title:'待审核', status:0,power:'caseinfo.query.status0'},
	{ title:'已审核', status:1,power:'caseinfo.query.status1'},
	{ title:'异常信息', status:-2,power:'caseinfo.query.status2'},
	{ title:'已作废', status:-1,power:'caseinfo.query.status3'},
	{ title:'未出报告', status:100,value:0,power:'caseinfo.query.report_state0'},
	{ title:'待出报告', status:101,value:1,power:'caseinfo.query.report_state1'},
	{ title:'已出报告', status:102,value:2,power:'caseinfo.query.report_state2'},
	{ title:'异常报告', status:103,value:-2,power:'caseinfo.query.report_state3'}
]
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		pag: {},
		selectedKeys:[],
		selectedRows:[],
		// 搜索表单列表
		forms: [
			{ label: '医院名称',		name: 'hosp_id',		type:'select',		loading:true,		idStr:'uuid',		nameStr:'hospName' },
			{ label: '条码号',		name: 'spec_code' },
			{ label: '病人姓名',		name: 'patient_name' },
			{ label: '录入时间',		names: ['create_at_start','create_at_end'], 	type:'date-range', 	loading:true,	name:'jz-time' },
			{ label: '证件号',		name: 'card_no' },
			{ label: '病人电话',		name: 'patient_phone' },
			{ label: '采集类型',		name: 'isMultiple',			type:'select',		data:MultipleType },
			{ label: '受检类型',		name: 'checkType',			type:'select',		data:CheckType },
			{ label: '采样时间',		names: ['coll_time_start','coll_time_end'], 	type:'date-range', 	loading:true,	name:'jz-time1' },
		],
		powerT: 1,
		key:0
	}
	model = {}
	hostData = []
	permissions = {uploadexcel:1,status:1,update:1,chhosp:1,download:1 }
	
	tabsArr = []
	componentDidMount(){
		const {ban_btn,ban_field} = $fn.local('permissions')
		if($fn.hasArray(ban_btn)){		// 按钮权限
			if(ban_btn.includes('caseinfo.uploadexcel')){		// 导入基本资料
				this.permissions.uploadexcel = 0
			}
			if(ban_btn.includes('caseinfo.status')){		// 审核、作废、恢复、异常
				this.permissions.status = 0
			}
			if(ban_btn.includes('caseinfo.update')){		// 修改采样时间
				this.permissions.update = 0
			}
			if(ban_btn.includes('caseinfo.chhosp')){		// 修改医院
				this.permissions.chhosp = 0
			}
			if(ban_btn.includes('caseinfo.download')){		// 导出
				this.permissions.download = 0
			}
		}
		if($fn.hasArray(ban_field)){
			this.tabsArr = tabsData.filter(v =>!ban_field.includes(v.power))
		}else{
			this.tabsArr = tabsData
		}
		if(this.tabsArr.length){
			const i = $fn.local('xgxt-jbxi-index')
			this.index = (i && i<=this.tabsArr.length-1)?i:0
			this.status = this.tabsArr[this.index]['status']
			this.setState({key:this.state.key+1})
			this.getSelect()
		}else{
			this.setState({powerT:0})
		}
	}
	onTime =  () => {
		$time.then(f=>{
			const arr = f.duration['2-9-12']()
			this.resetModel = { create_at_start: arr[0], create_at_end: arr[1], 'jz-time':arr }
			this.model = $fn.copy(this.resetModel)
			this.fetch()
		})
	}
	// 获取下拉数据
	getSelect = () => {
		const { forms } = this.state
		
		$cache.then( async f => {
			// 医院
			this.hostData = await f.getCache({ api:COVIDUrl+'Hospital/query',param:{page:1,page_num:10000,status:1} })
			$fn.setRow( forms, 'hosp_id', this.hostData )
			this.setState({ forms })
			this.onTime()
		})
	}
	
	
	
	// paging
	fetch = () => {
		let param = {}
		if(+this.status>=100){
			this.tabsArr.forEach(v=>{
				if(+v.status === +this.status){
					param = {report_state:v.value}
				}
			})
		}else{
			param = {status:this.status}
		}
		$fn.fetch.call(this, COVIDUrl+'caseinfo/query',{param, COVID:true} )
	}
	
	// 表单
	cols = [
		{ title: '申请单条码', 		dataIndex: 'specCode', 			width:130 },
		{ title: '审核状态', 		dataIndex: 'status', 			...$fn.table.status,	render: text => $fn.getState(Status,text) },
		{ title: '受检人姓名', 		dataIndex: 'patientName', 		...$fn.table.name },
		{ title: '性别', 			dataIndex: 'sex', 				...$fn.table.sex, 		render: text => $fn.getState(Sex,text) },
		{ title: '年龄', 			dataIndex: 'age', 				...$fn.table.age },
		{ title: '受检人电话', 		dataIndex: 'patientPhone', 		...$fn.table.phone },
		{ title: '受检类型', 		dataIndex: 'checkType', 		width:100,	render: text => $fn.getState(CheckType,text) },
		{ title: '受检人类型', 		dataIndex: 'caseType', 			width:120,				render: text => $fn.getState(CaseType,text) },
		{ title: '采样时间', 		dataIndex: 'collTime',  			...$fn.table.time },
		{ title: '录入时间', 		dataIndex: 'createdAt',  			...$fn.table.time },
		{ title: '送检单位', 		dataIndex: 'hospId', 			width:180,	render: text => $fn.getState(this.hostData,text,'hospName','uuid') },
		{ title: '证件类型', 		dataIndex: 'cardType', 			...$fn.table.card_type,	render: text => $fn.getState(CardType,text) },
		{ title: '证件号', 			dataIndex: 'cardNo', 			...$fn.table.idcard },
		{ title: '采集类型', 		dataIndex: 'isMultiple', 		width:100,	render: text => $fn.getState(MultipleType,text) },
		{ title: '送检科室', 		dataIndex: 'departmentName', 	width:180 },
		{ title: '送检医生', 		dataIndex: 'doctor', 			...$fn.table.name },
		{ title: '医生电话', 		dataIndex: 'doctorPhone', 		...$fn.table.phone },
		{ title: '医院标识', 		dataIndex: 'hospRemark', 			width:150 },
		{ title: '医院说明', 		dataIndex: 'hospText', 				width:180 },
		{ title: '临床诊断', 		dataIndex: 'clinicalDiagnosis', 	width:180 },
		{ title: '备注', 			dataIndex: 'remark', 			width:180 },
	]
	
	// 操作按钮
	controls = () => {
		const { selectedKeys, selectedRows } = this.state
		let specArr = selectedRows.map(v=>v.specCode)		// 选中条码
		specArr = Array.from(new Set(specArr))
		const uuids = selectedKeys.join(',')
		const {uploadexcel,status,update,chhosp,download } = this.permissions
		return [
			uploadexcel && Controls.imports.call(this, COVIDUrl + 'caseinfo/uploadExcel',{ label:'导入基本资料', fileName:'upfile',covid:true }),
			(status && (+this.status===0||+this.status===2))&&Confirm.call(this, '批量审核', COVIDUrl+'caseinfo/status', { isKeys:1, query:{ status:1,uuids } }),
			(status && +this.status!==-1)&&Confirm.call(this, '批量作废', COVIDUrl+'caseinfo/status', { isKeys:1, query:{ status:-1,uuids } }),
			(status && (+this.status===-1||+this.status===-2))&&Confirm.call(this, '批量恢复', COVIDUrl+'caseinfo/status', { isKeys:1, query:{ status:0,uuids } }),
			(status && +this.status!==-2)&&Controls.click.call(this, '批量异常', ()=>{
				this.aInfoModal.open(uuids,specArr)
			}, { isKeys:1 }),
			// Controls.click.call(this, '客户变更', ()=>this.hospModifyModal.open(), {code: 'F7'} ),
			update && Controls.click.call(this, '修改采样时间', ()=> this.sampTimeModalRef.open(uuids), {isKeys:1}),
			chhosp && Controls.click.call(this, '修改医院', ()=>this.changeHospModal.open(uuids), {isKeys:1} ),
			// Controls.click.call(this, '修改条码', ()=>this.changeSpecModal.open(uuids), {isKeys:1} ),
			
			download && Controls.click.call(this,'导出', ()=>{
				let statusParam
				if(+this.status>=100){
					this.tabsArr.forEach(v=>{
						if(+v.status === +this.status){
							statusParam = {report_state:v.value}
						}
					})
				}else{
					statusParam = {status:this.status}
				}
				const param = {...this.model,...statusParam}
				$http.submit(null, COVIDUrl+'caseinfo/download', { param }).then((data)=>{
					if(data){
						window.open(`${COVIDUrl}download?rand=${data}`)
					}
				})
			},{ghost:true})
		]
	}
	
	render(){
		return (
			<>
				<Page title='' nobc >
					{this.state.powerT ? <><div className='fxmj bcf'>
						<Tabs
							key={this.state.key}
							data={ this.tabsArr } defaultActiveKey = { this.index }
							onTabs = { ({ status },index) => {
								this.status = status
								this.setState({data:[],selectedKeys:[],selectedRows:[]})
								this.fetch()
								$fn.local('xgxt-jbxi-index', index)
							}}
						/>
						<div><BtnGroup controls={this.controls()} /></div>
					</div>
					{/* 搜索 */}
					{ SearchForm.call(this, {timeStr:'2-9-12'}) }
					<section className='ex fx mt5 '>
						<div className='h ex rel fv'  >
							{/* 表格 */}
							{ Table.call(this, { wrapClassName:'mr5', onRow: ( {uuid} )=>{
								this.patientDetailRef.setValue(uuid)
							}}) }
						</div>
						<div className=' h fv bor1' style={{width:500, minWidth:400}}>
							{/* 病人详细信息 */}
							<PatientDetail onRef={ ref => this.patientDetailRef = ref } 
								onNext = {this.nextData}
								onRefresh = {this.fetch}
							/>
						</div>
					</section></> :
					<div className='fxmc ex'>您没有查看权限，请添加权限</div>
					}
				</Page>
				{/* 客户变更 */}
				<HospModifyModal onRef={ref=>this.hospModifyModal=ref} onRefresh={this.fetch}/>
				{/* 修改采样时间 */}
				<SampTimeModal onRef={ref=>this.sampTimeModalRef=ref} onRefresh={this.fetch}/>
				{/* 修改医院 */}
				<ChangeHospModal onRef={ref=>this.changeHospModal=ref} onRefresh={this.fetch}/>
				{/* 修改条码 */}
				<ChangeSpecModal onRef={ref=>this.changeSpecModal=ref} onRefresh={this.fetch}/>
				{/* 批量异常 */}
				<AbnormalInfoModal onRef={ref=>this.aInfoModal=ref} onRefresh={()=>{
					this.setState({selectedKeys:[],selectedRows:[]})
					this.fetch()
				}}/>
			</>
		)
	}
}

export default Index